﻿using System.Activities;
using System.IO;
using log4net;
using Reactor.Environment;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class ObtainServiceInstallLocations : CodeActivity
    {
        [RequiredArgument]
        public InArgument<ServiceIdentifier> ServiceIdentifier { get; set; }

        [RequiredArgument]
        public InArgument<ILog> Logger { get; set; }

        public OutArgument<string> TargetServiceInstallPath { get; set; }
        public OutArgument<DirectoryInfo> TargetServiceInstallDirectory { get; set; }

        #region Overrides of CodeActivity

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            var logger = context.GetValue(Logger);
            var serviceIdentifier = context.GetValue(ServiceIdentifier);

            var serviceInstallsRootPath = Context.Configuration.GetConfigurationValue("Core.ServiceInstallsRootPath");
            var serviceInstallPath = Path.Combine(serviceInstallsRootPath, serviceIdentifier.ToString());
            context.SetValue(TargetServiceInstallPath, serviceInstallPath);

            var installDirectory = (Directory.Exists(serviceInstallPath)) ? new DirectoryInfo(serviceInstallPath) : null;
            if(installDirectory == null)
            {
                if(logger.IsDebugEnabled)
                    logger.DebugFormat("Cannot find service install directory at: {0}", serviceInstallPath);
            }
            else
            {
                if (logger.IsDebugEnabled)
                    logger.DebugFormat("Discovered service install directory at: {0}", serviceInstallPath);

                context.SetValue(TargetServiceInstallDirectory, installDirectory);
            }
        }

        #endregion
    }
}
